import * as Cesium from 'cesium'
import type { Viewer } from 'cesium'
import type { Map } from 'ol'
import View from 'ol/View'

/**
 * 计算场景中心点
 * @param viewer
 * @returns 场景中心点
 */
export function getSceneCenter(viewer: Viewer) {
  const cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(viewer.camera.position)
  const longitude = Cesium.Math.toDegrees(cartographic.longitude)
  const latitude = Cesium.Math.toDegrees(cartographic.latitude)
  const altitude = cartographic.height
  return { longitude, latitude, altitude }
}

/**
 * 计算地图的zoom
 * @param height 相机高度
 * @returns 地图的zoom
 */
function computeZoom(height: number) {
  const heightArr = [
    32802741.16421673, 23967390.5342611, 12109133.282591399, 7544339.942150029, 4013980.746760576, 2153098.45872719, 1031519.751307045, 594367.296565025, 342677.25083245104,
    164632.97755610794, 76977.64690613124, 36875.262696890095, 17669.269867698094, 10253.27377477659, 4913.00444094621, 3400.8921034522014, 1958.669367726067, 758.7914964838986,
    525.1914307070838, 363.3647775209164
  ]
  let zoom = 0
  let minDiff = Math.abs(height - heightArr[0])
  for (let i = 1; i < heightArr.length; i++) {
    const diff = Math.abs(height - heightArr[i])
    if (diff < minDiff) {
      minDiff = diff
      zoom = i
    }
  }
  return zoom
}

/**
 * 场景相机变化后改变地图中心点与 zoom
 * @param viewer 场景
 * @param map 地图
 */
export default function onSceneCenterChange(viewer: Viewer, map: Map) {
  const { longitude, latitude, altitude } = getSceneCenter(viewer)
  map.setView(
    new View({
      center: [longitude, latitude],
      zoom: computeZoom(altitude),
      projection: 'EPSG:4326',
      multiWorld: true
    })
  )
}
